<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="反馈类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择反馈类型"
          clearable
          style="width: 240px"
        >
          <el-option label="BUG反馈" value="1" />
          <el-option label="意见反馈" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否回复" prop="isReply">
        <el-select
          v-model="queryParams.isReply"
          placeholder="请选择是否回复"
          clearable
          style="width: 240px"
        >
          <el-option label="是" :value="true" />
          <el-option label="否" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否精选" prop="isChoice">
        <el-select
          v-model="queryParams.isChoice"
          placeholder="请选择是否精选"
          clearable
          style="width: 240px"
        >
          <el-option label="是" :value="true" />
          <el-option label="否" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="feedbackList">
      <el-table-column label="反馈类型" align="center" prop="type">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.type === 1" type="danger">BUG反馈</el-tag>
          <el-tag v-else-if="scope.row.type === 2" type="warning">意见反馈</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="反馈内容" align="center" prop="userFeedback" :show-overflow-tooltip="true" />
      <el-table-column label="是否精选" align="center" prop="isChoice">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isChoice" type="success">是</el-tag>
          <el-tag v-else type="info">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否已回复" align="center" prop="isReply">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isReply" type="success">是</el-tag>
          <el-tag v-else type="info">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="120"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 反馈详情对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-row>
        <el-col :span="12">
          <!-- 用户信息 -->
          <el-card class="user-info-card" shadow="never">
            <div slot="header" class="clearfix">
              <span>用户信息</span>
            </div>
            <div class="user-info">
              <div class="avatar-container">
                <el-avatar :size="80" :src="form.avatar" />
              </div>
              <div class="user-details">
                <div class="user-name">名称：{{ form.userName }}</div>
                <div class="user-cyid">次元身份ID: {{ form.cyId }}</div>
              </div>
            </div>
          </el-card>
          
          <!-- 反馈内容 -->
          <el-card class="content-card" shadow="never">
            <div slot="header" class="clearfix">
              <span>反馈内容</span>
            </div>
            <div class="feedback-content">
              <div class="content-text">{{ form.userFeedback }}</div>
            </div>
          </el-card>
          
          <!-- 用户上传的媒体文件 -->
          <el-card class="media-card" shadow="never" v-if="form.userImages && form.userImages.length > 0 || form.userVideoList && form.userVideoList.length > 0">
            <div slot="header" class="clearfix">
              <span>用户上传的媒体文件</span>
            </div>
            <div class="media-container">
              <!-- 图片展示 -->
              <div v-for="(item, index) in form.userImages" :key="'img-' + index" class="media-item">
                <img :src="item.compressUrl" class="media-image" @click="previewImage(item.imageUrl)" />
              </div>
              <!-- 视频展示 -->
              <div v-for="(item, index) in form.userVideoList" :key="'video-' + index" class="media-item video-item">
                <video :src="item.imageUrl" class="media-video" controls />
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="12">
          <el-form ref="replyForm" :model="replyForm" label-width="80px">
            <!-- 状态提示 -->
            <div v-if="feedbackStype" class="status-tip">
              <el-alert
                title="此反馈已回复，无法再次编辑"
                type="info"
                :closable="false"
                show-icon>
              </el-alert>
            </div>
            <el-form-item label="是否精选">
              <el-switch
                v-model="replyForm.isChoice"
                active-text="是"
                inactive-text="否"
                @change="handleChoiceChange"
                :disabled="feedbackStype"
              />
            </el-form-item>
            <el-form-item label="回复内容">
              <!-- <Editor
                v-model="replyForm.replyContent"
                :min-height="200"
                placeholder="请输入回复内容..."
              /> -->
              <el-input
                type="textarea"
                placeholder="请输入内容"
                v-model="replyForm.replyContent"
                :disabled="feedbackStype">
              </el-input>
            </el-form-item>
            <el-form-item label="上传图片" v-if=" replyForm.videoList.length == 0">
              <div class="upload-tip">注意：图片和视频只能选择一种上传</div>
              <el-upload
                :action="uploadUrl"
                :headers="headers"
                :on-success="handleImageSuccess"
                :on-remove="handleImageRemove"
                :file-list="replyForm.imageList"
                list-type="picture-card"
                :limit="9"
                accept="image/*"
                :on-preview="handleImagePreview"
                :disabled="feedbackStype"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="上传视频" v-if="replyForm.imageList.length == 0 && replyForm.videoList.length == 0">
              <div class="upload-tip">注意：图片和视频只能选择一种上传</div>
              <el-upload
                :action="uploadUrl"
                :headers="headers"
                :on-success="handleVideoSuccess"
                :on-remove="handleVideoRemove"
                :file-list="replyForm.videoList"
                list-type="text"
                :limit="1"
                accept="video/*"
                :on-preview="handleVideoPreview"
                :disabled="feedbackStype"
              >
                <el-button size="small" type="primary" :disabled="feedbackStype" >点击上传视频</el-button>
              </el-upload>
            </el-form-item>
            
            <!-- 已上传的图片显示 -->
            <!-- <el-form-item label="已上传图片" v-if="replyForm.imageList.length > 0">
              <div class="uploaded-files">
                <div v-for="(file, index) in replyForm.imageList" :key="index" class="file-item">
                  <img :src="file" class="file-preview" @click="handleImagePreview(file)" />
                  <el-button size="mini" type="danger" @click="removeImage(index)">删除</el-button>
                </div>
              </div>
            </el-form-item> -->
            
            <!-- 已上传的视频显示 -->
            <el-form-item label="已上传视频" v-if="replyForm.videoList.length > 0">
              <div class="uploaded-files">
                <div v-for="(file, index) in replyForm.videoList" :key="index" class="file-item video-file-item">
                  <video :src="file.response.url" class="file-preview video-preview" controls />
                  <el-button size="mini" type="danger" @click="removeVideo(index)" :disabled="feedbackStype">删除</el-button>
                </div>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitReply" :disabled="feedbackStype">提交回复</el-button>
              <el-button @click="cancel">取消</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog :visible.sync="previewVisible" title="图片预览" width="600px" append-to-body>
      <img :src="previewImageUrl" style="width: 100%;" />
    </el-dialog>
  </div>
</template>

<script>
import { listFeedback, updateFeedback, submitPunishFeedback } from "@/api/user/feedback";
import { getToken } from "@/utils/auth";
import Editor from "@/components/Editor";
import { mapState } from 'vuex'
export default {
  name: "Feedback",
  components: { Editor },
  computed: {
    ...mapState({
      punishId: state => state.user.id
    })
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 反馈表格数据
      feedbackList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        searchType: 1,
        type: undefined,
        isReply: undefined,
        isChoice: undefined
      },
      // 表单参数
      form: {},
      // 回复表单参数
      replyForm: {
        isChoice: false,
        replyContent: "",
        imageList: [],
        videoList: [],
        hasImage: false,
        hasVideo: false
      },
      feedbackStype:false,
      // 上传地址
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      // 上传请求头
      headers: {
        Authorization: "Bearer " + getToken()
      },
      // 图片预览
      previewVisible: false,
      previewImageUrl: ""
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询反馈列表 */
    getList() {
      this.loading = true;
      listFeedback(this.queryParams).then(response => {
        console.log(response.data,"==========================================>");
        
        this.feedbackList = response.data;
        this.total = response.code;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 查看按钮操作 */
    handleView(row) {
      // 先清空所有数据
      this.reset();
      
      // 填充新的数据
      this.form = row;
      // 确保 userVideoList 数据正确赋值
      if (row.userVideoList && row.userVideoList.length > 0) {
        this.form.userVideoList = row.userVideoList;
      } else {
        this.form.userVideoList = [];
      }
      this.replyForm.isChoice = row.isChoice;
      this.replyForm.replyContent = row.punishFeedback || "";
      this.replyForm.userFeedback = row.userFeedback;
      this.feedbackStype =  row.isReply?true:false;
              // 处理已有的回复图片
        if (row.punishImages && row.punishImages.length > 0) {
          // 为每个图片对象添加 Element UI upload 组件需要的属性
          const processedImages = row.punishImages.map(item => ({
            ...item,
            url: item.imageUrl, // 使用原图作为显示
            name: item.imageUrl.split('/').pop(), // 从URL中提取文件名
            status: 'success' // 标记为已上传成功状态
          }));
          
          this.replyForm.imageList = processedImages;
          console.log(this.replyForm.imageList,"==========================================>355");
          this.replyForm.compressedFileUrl = row.punishImages.map(item => item.compressUrl);
          this.replyForm.hasImage = true;
          this.replyForm.hasVideo = false;
        } else {
          this.replyForm.imageList = [];
          this.replyForm.compressedFileUrl = [];
          this.replyForm.hasImage = false;
        } 

              // 处理已有的回复视频
        if (row.punishVideoList && row.punishVideoList.length > 0) {
          console.log(row.punishVideoList,"==========================================>362");
          this.replyForm.videoList = [];
          for(var i=0; i<row.punishVideoList.length;i++){
            this.replyForm.videoList.push({
              response: {
                url: row.punishVideoList[i].imageUrl
              }
            })
          }
          this.replyForm.hasVideo = true;
          this.replyForm.hasImage = false;
          this.replyForm.imageList = [];
          this.replyForm.compressedFileUrl = [];
        } else {
          this.replyForm.videoList = [];
          this.replyForm.hasVideo = false;
        } 

      this.open = true;
      this.title = "反馈详情";
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userVideoList: [],
        userImages: []
      };
      this.replyForm = {
        isChoice: false,
        replyContent: "",
        imageList: [],
        videoList: [],
        compressedFileUrl: [],
        hasImage: false,
        hasVideo: false,
        userFeedback: ""
      };
    },
    // 判断是否为图片
    isImage(url) {
      if (!url) return false;
      const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'];
      return imageExtensions.some(ext => url.toLowerCase().includes(ext));
    },
    // 判断是否为视频
    isVideo(url) {
      if (!url) return false;
      const videoExtensions = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm'];
      return videoExtensions.some(ext => url.toLowerCase().includes(ext));
    },
    // 预览图片
    previewImage(url) {
      console.log(url,"==========================================>");
      this.previewImageUrl = url;
      this.previewVisible = true;
    },
    // 精选状态改变
    handleChoiceChange(value) {
      this.replyForm.isChoice = value;
    },
    // 图片上传成功
    handleImageSuccess(response, file, fileList) {
      if (response.code === 200) {
        // 为每个文件添加正确的url属性用于预览
        const updatedFileList = fileList.map(item => {
          if (item.response && item.response.fileName) {
            // 如果是新上传的文件，使用服务器返回的URL
            return {
              ...item,
              url: item.response.url,
              name: item.response.fileName,
              status: 'success'
            };
          }
          return item;
        });
        console.log(fileList,"==========================================>441");
        // 更新图片列表，保持完整的对象结构
        this.replyForm.imageList = updatedFileList;
        this.replyForm.compressedFileUrl = updatedFileList.map(item => 
          item.response ? item.response.compressedFileUrl : item.compressUrl
        );
        console.log(updatedFileList,"==========================================>447");
        console.log(this.replyForm.imageList,"==========================================>447");
        this.replyForm.hasImage = true;
        this.replyForm.hasVideo = false;
        this.replyForm.videoList = [];
        this.$message.success("图片上传成功");
      } else {
        this.$message.error("图片上传失败");
      }
    },
    // 图片移除
    handleImageRemove(file, fileList) {
      // 更新图片列表，保持完整的对象结构
      this.replyForm.imageList = fileList;
      this.replyForm.compressedFileUrl = fileList.map(item => 
        item.response ? item.response.compressedFileUrl : item.compressUrl
      );
      this.replyForm.hasImage = fileList.length > 0;
    },
    // 图片预览
    handleImagePreview(file) {
      // 如果file是字符串（URL），直接使用；如果是对象，使用file.url
      this.previewImageUrl = typeof file === 'string' ? file : file.url;
      this.previewVisible = true;
    },
    // 视频上传成功
    handleVideoSuccess(response, file, fileList) {
      if (response.code === 200) {
        // 为每个文件添加正确的url属性用于预览
        const updatedFileList = fileList.map(item => {
          if (item.response && item.response.fileName) {
            // 如果是新上传的文件，使用服务器返回的URL
            return {
              ...item,
              url: process.env.VUE_APP_BASE_API + "/common/download?fileName=" + item.response.fileName
            };
          }
          return item;
        });
        this.replyForm.videoList = updatedFileList
        this.replyForm.imageList = updatedFileList.map(item => item.response.url);
        this.replyForm.hasVideo = true;
        this.replyForm.hasImage = false;
        this.$message.success("视频上传成功");
      } else {
        this.$message.error("视频上传失败");
      }
    },
    // 视频移除
    handleVideoRemove(file, fileList) {
      this.replyForm.imageList = fileList;
      this.replyForm.hasVideo = fileList.length > 0;
    },
    // 视频预览
    handleVideoPreview(file) {
      // 对于视频，我们可以打开新窗口播放
      window.open(file.url, '_blank');
    },
    // 删除图片
    removeImage(index) {
      this.replyForm.imageList.splice(index, 1);
      this.replyForm.compressedFileUrl.splice(index, 1);
      this.replyForm.hasImage = this.replyForm.imageList.length > 0;
      if (this.replyForm.imageList.length === 0) {
        this.replyForm.hasImage = false;
      }
    },
    // 删除视频
    removeVideo(index) {
      this.replyForm.videoList.splice(index, 1);
      this.replyForm.imageList.splice(index, 1);
      this.replyForm.hasVideo = this.replyForm.videoList.length > 0;
      if (this.replyForm.videoList.length === 0) {
        this.replyForm.hasVideo = false;
      }
    },
    // 提交回复
    submitReply() {
      const imgs = []
      for(var i=0; i<this.replyForm.imageList.length;i++){
        if(this.replyForm.imageList[i].response){
          imgs.push({
            images: this.replyForm.imageList[i].response.url,
            compressedImages: this.replyForm.compressedFileUrl[i]
          })
        }else{
          imgs.push({
            images: this.replyForm.imageList[i],
            compressedImages: this.replyForm.imageList[i]
          })
        }

        // const item = this.replyForm.imageList[i];
        // imgs.push({
        //   images: item.response ? item.response.url : item.url, // 新上传的用response.url，已有的用url
        //   compressedImages: this.replyForm.compressedFileUrl[i]
        // })
      }
      const data = {
        id: this.form.id,
        isChoice: this.replyForm.isChoice,
        punishId: this.punishId,
        punishFeedback: this.replyForm.replyContent,
        punishImages: imgs,
      };
      // console.log( "data:", data);
      // return;
      // 调用惩罚类型接口
      submitPunishFeedback(data).then(response => {
        if (response.code === 200) {
          this.$modal.msgSuccess("回复成功");
          this.open = false;
          this.getList();
        } else {
          this.$message.error(response.msg || "回复失败");
        }
      }).catch(error => {
        console.error("提交回复失败:", error);
        this.$message.error("回复失败，请重试");
      });
    }
  }
};
</script>

<style scoped>
.media-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.media-item {
  width: 100px;
  height: 100px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
}

.media-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.media-video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-item {
  width: 300px !important;
  height: 200px !important;
}

.video-item .media-video {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.user-info-card,
.content-card,
.media-card {
  margin-bottom: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  /* padding: 10px 0; */
}

.avatar-container {
  margin-right: 20px;
}

.user-details {
  flex: 1;
}

.user-name {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.user-cyid {
  font-size: 14px;
  color: #606266;
}

.feedback-content {
  padding: 10px 0;
}

.content-text {
  font-size: 14px;
  line-height: 1.6;
  color: #303133;
  text-align: center;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  min-height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.media-card .media-container {
  margin-top: 10px;
}

.media-card .media-item {
  width: 120px;
  height: 120px;
}

.media-card .media-image:hover {
  transform: scale(1.05);
  transition: transform 0.2s ease;
}

.uploaded-files {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.file-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.file-preview {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #d9d9d9;
}

.file-preview:hover {
  transform: scale(1.05);
  transition: transform 0.2s ease;
}

.video-file-item {
  width: 300px;
}

.video-preview {
  width: 300px !important;
  height: 200px !important;
  object-fit: contain;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-bottom: 10px;
  padding: 5px 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.status-tip {
  margin-bottom: 20px;
}
</style>
